package com.sslite.dao;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.sslite.model.MetaData;
import com.sslite.util.SSLiteProperties;
import com.sslite.util.Utility;

public class MetaDataDao {

	public static void main(String[] args) throws Exception{
		pullAndSaveMetaData( GoogleStockScreenerDao.getSymbols() );
		System.out.println( "Done." );
	}
	
	public static List<MetaData> getMetaDataFor(final List<String> symbols) throws Exception{
		String content = Utility.getContent( new File(SSLiteProperties.METADATA_CSV_FILE_PATH.getValue() ).toURL().toString() );
		final List<MetaData> metaDataList = new ArrayList<MetaData>();

		// Populate list of Marginable stocks from sogotrade.
		final List<String> sogoMarginables = new ArrayList<String>();
		String shortList = "";
		try{
			shortList = Utility.getContent( "http://wangvestonline.com/sogotrade/list/shortlist.txt" );
		}
		catch(Exception e){
			System.out.println( "\n\nUnable to pull shortlist.txt from wangvestonline.com: " +e.getMessage()+ "\n\n" );
		}
		for( String line : shortList.split("\n") ){
			sogoMarginables.add( line.split("\t")[0] );
		}
		//
		
		String[] rows = content.split("\n");
		for( int i=1; i<rows.length; i++ ){
			MetaData metaData = null;
			String cols[] = rows[i].split("[,]");
			try{
				final String symbol = cols[0].trim();
				if( !symbols.contains( symbol ) ){
					continue;
				}
				
				metaData = new MetaData(symbol);
				metaData.setInSogotradeShortList( sogoMarginables.contains(symbol) );
				
				final Long sharesOutstanding = new Long( cols[2].trim() );
				metaData.setSharesOutstanding(sharesOutstanding);
			}
			catch(Exception e){
				System.out.println( "Exception in reading MetaData: " +rows[i] );
			}
			metaDataList.add( metaData );
		}
		
		Collections.sort(metaDataList, new Comparator<MetaData>(){
			@Override
			public int compare(MetaData o1, MetaData o2) {
				return o1.getSymbol().compareTo( o2.getSymbol() );
			}
		});
		
		return metaDataList;
	}
	
	/**
	 * For processing quote feed.
	 * 
	 */
	private static void pullAndSaveMetaData(List<String> list) throws Exception {
		final StringBuilder sb = new StringBuilder();
		sb.append("Symbol,Exchange,SharesOutstanding,AbbrSharesOutstanding").append("\n");
		for (String symbol : list) {
			symbol = symbol.trim();
			//System.out.println("Pulling [" + symbol + "]");

			try {
				String exchange = "";
				final StringBuffer sbMain = new StringBuffer(Utility.getContent(SSLiteProperties.CNBC_URL.getValue() + symbol));
				int indexOfExchange = sbMain.indexOf( "\"exchange\":" );
				if( indexOfExchange != -1 ){
					int startIndex = indexOfExchange+11;
					exchange = sbMain.substring( startIndex, sbMain.indexOf( ",", startIndex ) ).replaceAll("\"", "");
				}
				
				// Start: Pull Data
				final StringBuffer sbExtn = new StringBuffer(Utility.getContent(SSLiteProperties.CNBC_URL_EXTN.getValue() + symbol));

				String sharesOutstanding = "";
				int index5 = sbExtn.indexOf("Shares Outstanding");
				if (index5 != -1) {
					sharesOutstanding = sbExtn.substring(index5 + 38, sbExtn.indexOf("<", index5 + 38));
					sharesOutstanding = sharesOutstanding.trim().replaceAll(",", "");
				}
				//System.out.println( "INSERT INTO SYMBOL_METADATA VALUES('"+ symbol+"', '"+sharesOutstanding+"', "+Utility.convertFinancials(sharesOutstanding)+ ");" );
				System.out.println(symbol + ","+ exchange + "," + Utility.convertFinancials(sharesOutstanding) + "," + sharesOutstanding);
				sb.append( symbol + "," + exchange + "," + Utility.convertFinancials(sharesOutstanding) + "," + sharesOutstanding ).append("\n");
			} catch (Exception e) {
				System.out.println( "Error in pulling "+symbol );
				sb.append( "Error in pulling " +symbol ).append("\n");
				e.printStackTrace();
			}
			Utility.saveContent(SSLiteProperties.METADATA_CSV_FILE_PATH.getValue(), sb.toString());
		}
	}
}
